#include "framewindow.h"
#include "manualthread.h"

#include <QDateTime>
#include <QMap>

#include <QDebug>

ManualThread::ManualThread(FrameWindow *frameWindow)
{
    this->parent = frameWindow;
}



ManualThread::~ManualThread()
{
    quit();
    wait();
}


int ManualThread::init()
{

    connect(this,&ManualThread::manualSendAndReceive,parent
            ,&FrameWindow::onManualSendAndReceive);

    moveToThread(QThread::currentThread());

    COMMap = new QMap<QString,SerialPortsManager*>;

    foreach ( QString comName,parent->COMLists) {

        SerialPortsManager  *manager = new SerialPortsManager(parent);
        QSerialPort *COM = new QSerialPort();
        manager->serialPort = COM;

        COM->moveToThread(this);
        COMMap->insert(comName,manager);

    }

    return 0;
}



void ManualThread::run()
{
    init();
    wait(5000);
    long loop = 0;
    QString COMName;


    //串口循环
    QMap<QString, SerialPortsManager*>::iterator iter1 = COMMap->begin();
    while (iter1 !=COMMap->end())
    {
        loop++;

        COMName = iter1.key();
        qDebug() << "串口名称： "<<COMName;
        iter1.value()->moveToThread(QThread::currentThread());

        iter1.value()->configCOM();
        iter1.value()->openCOM(COMName);

        /*
         * 单个命令
         */
        qDebug() <<QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss:zzz")<<COMName<<"发送：";
        qDebug() <<parent->ManualCommand;

        iter1.value()->sendCOM(parent->ManualCommand.toLocal8Bit());               
        emit manualSendAndReceive(COMName,parent->ManualCommand,"发送");

        msleep(500);
        if (iter1.value()->waitForReceive(5000))
        {

            //从缓冲区中读取数据
            QByteArray buffer = iter1.value()->serialPort->readAll();

            qDebug() <<QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss:zzz")<<COMName<<"接收：";
            qDebug() <<buffer;

            iter1.value()->newReceived=buffer;
            dealData(COMName,parent->ManualCommand  ,iter1.value()->newReceived);

        }

        iter1.value()->closeCOM();

        iter1++; //
    }
}

int ManualThread::dealData(QString COM, QString  comm, QByteArray rec)
{
    QString recString;

    QString strRec;
    strRec.prepend(rec);
    strRec = strRec.trimmed();

    QStringList  strs =strRec.split(QRegExp("[\r\n]"),QString::SkipEmptyParts);

    //temp+=send;

    foreach (QString response, strs)
    {
        if(comm==response){
            qDebug() <<comm<<" == "<<response;
        }

        recString += response+"  ";
    }

    emit manualSendAndReceive(COM,recString,"接收");

    return 0;

}


